package com.ctshk.rpc.scenic.service.impl.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctshk.common.constant.ElasticSearchConstant;
import com.ctshk.common.dto.Result;
import com.ctshk.common.model.PageResponse;
import com.ctshk.rpc.scenic.dto.app.ScenicProductEsDTO;
import com.ctshk.rpc.scenic.dto.app.inner.ScenicTicketListDTO;
import com.ctshk.rpc.scenic.entity.ScenicProductCostStrategySpecStock;
import com.ctshk.rpc.scenic.mapper.ScenicProductCostStrategySpecStockMapper;
import com.ctshk.rpc.scenic.req.TicketRecommendReq;
import com.ctshk.rpc.scenic.service.app.IScenicTicketRecommendService;
import lombok.AllArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@DubboService
@AllArgsConstructor
public class ScenicTicketRecommendServiceImpl implements IScenicTicketRecommendService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    private ScenicProductCostStrategySpecStockMapper scenicProductCostStrategySpecStockMapper;

    @Override
    public Result<PageResponse<ScenicTicketListDTO>> selectTicketRecommendList(TicketRecommendReq req, Integer pageNum, Integer pageSize) {
        SearchRequest searchRequest = new SearchRequest(ElasticSearchConstant.SCENIC);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        {// 搜索条件
            if (req.getCityId() != null){
                // 城市ID
                boolQueryBuilder.filter( QueryBuilders.matchQuery("cityId", String.valueOf(req.getCityId())) );
            }
            // 渠道来源
            boolQueryBuilder.filter( QueryBuilders.matchQuery("channelId", String.valueOf(req.getChannelId())) );
            // 推荐
            boolQueryBuilder.should( QueryBuilders.matchQuery("isRecommend", 1) );
            // 已上架
            boolQueryBuilder.filter( QueryBuilders.matchQuery("status", 1) );
        }

        searchSourceBuilder.query(boolQueryBuilder);

        searchSourceBuilder.from(pageNum == null || pageNum == 0 ? 0 : (pageNum-1)*pageSize);
        searchSourceBuilder.size(pageSize);

        searchRequest.source(searchSourceBuilder);
        SearchResponse search = null;
        try{
            search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            if(search == null){
                return Result.success(PageResponse.empty(pageNum));
            }
            List<ScenicTicketListDTO> result = new ArrayList<>();
            SearchHits hits = search.getHits();
            long totalHits = hits.getTotalHits().value;
            for (SearchHit hit : hits) {
                ScenicProductEsDTO scenicProductEsDTO = JSON.parseObject(hit.getSourceAsString(), ScenicProductEsDTO.class);
                if(scenicProductEsDTO != null){
                    /*if (!Objects.isNull(req.getProductId()) && !Objects.isNull(scenicProductEsDTO.getProductId())){*/
                        if (req.getProductId() == null || !req.getProductId().equals(scenicProductEsDTO.getProductId())){
                            ScenicTicketListDTO scenicTicketListDTO = new ScenicTicketListDTO();
                            scenicTicketListDTO.setProductId(scenicProductEsDTO.getProductId());
                            scenicTicketListDTO.setTitle(scenicProductEsDTO.getProductName());
                            scenicTicketListDTO.setPrice(scenicProductEsDTO.getCostPrice());

                            BigDecimal rate = null;
                            List<ScenicProductCostStrategySpecStock> stocksObj = scenicProductCostStrategySpecStockMapper.quertCostPriceByid(scenicProductEsDTO.getProductId());
                            if (!Objects.isNull(stocksObj.get(0).getCostPrice())){
                                //获取成本价格
                                scenicTicketListDTO.setPrice(stocksObj.get(0).getCostPrice());
                                rate = stocksObj.get(0).getCostPrice();
                            }

                            Double price = scenicProductEsDTO.getExchangeRate();
                            //汇率
                            scenicTicketListDTO.setExchangeRate(scenicProductEsDTO.getExchangeRate());

                            BigDecimal mone = rate.multiply(BigDecimal.valueOf(price));
                            if (scenicProductEsDTO.getAmount() == null){
                                scenicTicketListDTO.setMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                        .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                            }else if (scenicProductEsDTO.getAmount() != null){
                                BigDecimal moneAttr = mone.add(scenicProductEsDTO.getAmount()).setScale(0,BigDecimal.ROUND_UP);
                                scenicTicketListDTO.setMoney(moneAttr
                                        .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                            }

                            scenicTicketListDTO.setChannelId(scenicProductEsDTO.getChannelId());
                            scenicTicketListDTO.setSign("熱門產品");
                            // 解析图片
                            String photosJson = scenicProductEsDTO.getPhotosJson();
                            if(photosJson != null){
                                List<JSONObject> jsonObjects = JSON.parseArray(photosJson, JSONObject.class);
                                for (JSONObject jsonObject : jsonObjects) {
                                    String url = (String) jsonObject.get("url");
                                    if(url != null){
                                        scenicTicketListDTO.setPng(url);
                                        break;
                                    }
                                }
                            }
                            result.add(scenicTicketListDTO);
                        /*}*/
                    }
                }
            }
            PageResponse<ScenicTicketListDTO> scenicTicketListDTOPageResponse = new PageResponse<>();
            scenicTicketListDTOPageResponse.setPageNo(pageNum);
            scenicTicketListDTOPageResponse.setPageSize(pageSize);
            scenicTicketListDTOPageResponse.setTotal(totalHits);
            scenicTicketListDTOPageResponse.setIsFirst(pageNum==0);
            scenicTicketListDTOPageResponse.setIsLast(pageNum*pageSize>=totalHits);
            scenicTicketListDTOPageResponse.setRecords(result);
            return Result.success(scenicTicketListDTOPageResponse);
        }catch (Exception e){
            e.printStackTrace();
            return Result.success(PageResponse.empty(pageNum));
        }
    }
}
